<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="请求id" prop="requestId">
        <el-input v-model="queryParams.requestId" placeholder="请输入请求id" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['genius:arith-cut-task:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['genius:arith-cut-task:removed']">删除</el-button>
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
          v-hasPermi="['genius:arith-cut-task:export']">导出</el-button>
      </el-col> -->
      <el-col :span="1.5">
        <el-upload action="/" :on-change="fileUpload" :auto-upload="false" :show-file-list="false" accept=".xls, .xlsx">
          <el-button type="success" plain icon="el-icon-upload" size="mini"
            >导入</el-button>
        </el-upload>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="ArithCutTaskList" @selection-change="handleSelectionChange" :default-sort = "{prop: 'id', order: 'descending'}">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column sortable label="序号" align="center" prop="id" />
      <el-table-column label="请求id" align="center" prop="requestId" />
      <el-table-column label="创建时间" align="center" prop="createTime" />
      <el-table-column label="文件地址" align="center" prop="dirPath" />
      <el-table-column label="任务状态" align="center" prop="status">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.status === 0" type="info">待处理</el-tag>
          <el-tag v-if="scope.row.status === 1" type="warning">处理中</el-tag>
          <el-tag v-if="scope.row.status === 2" type="success">处理完成</el-tag>
          <el-tag v-if="scope.row.status === -1" type="danger">处理失败</el-tag>
          <!-- {{ scope.row.status === 0 ? '待处理' : (scope.row.status === 1 ? '处理中' : '处理完成' ) }} -->
        </template>
      </el-table-column>
      <el-table-column label="总数" align="center" prop="total" />
      <el-table-column label="失败数" align="center" prop="failCount" />
      <el-table-column label="成功数" align="center" prop="successCount" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button v-if="scope.row.status === 0" size="mini" type="text" icon="el-icon-edit"
            @click="handleStartCut(scope.row)">开始切图</el-button>
          <!-- <el-button v-if="scope.row.status === 2" size="mini" type="text" icon="el-icon-edit"
            @click="handleDownload(scope.row)">下载</el-button> -->
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleDetail(scope.row)">详情</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
            v-hasPermi="['genius:arith-cut-task:removed']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改成列切图任务对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="上传图片">
          <el-upload ref="upload" accept=".jpg, .png, .txt" :action="upload.url" multiple :http-request="HttpUploadFile"
            :headers="upload.headers" :file-list="upload.fileList" :on-success="handleFileSuccess"
            :on-change="changeFileList" :on-remove="handleRemove" :data="getfileData()" :auto-upload="false">
            <el-button slot="trigger" size="small" type="primary">选取文件</el-button>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitUpload">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 详情展示框 -->
    <el-dialog title="图片处理详情" :visible.sync="detailDialog" width="1100px" append-to-body>
      <el-table v-loading="detailLoading" :data="detail_list">
        <el-table-column label="id" align="center" prop="id" />
        <el-table-column label="任务id" align="center" prop="taskId" />
        <el-table-column label="图片名称" align="center" prop="picName" />
        <!-- <el-table-column label="图片base64" align="center" prop="base64" /> -->
        <!-- <el-table-column label="算法处理结果" align="center" prop="algoResult" /> -->
        <el-table-column label="图片状态" align="center" prop="status">
          <template slot-scope="scope">
            <el-tag v-if="scope.row.status === 0" type="warning">待处理</el-tag>
            <el-tag v-if="scope.row.status === 1" type="success">处理完成</el-tag>
            <el-tag v-if="scope.row.status === -1" type="danger">处理失败</el-tag>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>
  </div>
</template>

<script>
import { listArithCutTask, getArithCutTask, removedArithCutTask, downloadMinImgZip, addArithCutTask, handleCutImage, getArithCutTaskDetails,uploadImage } from "@/api/genius/arith-cut-task";
import { getToken } from "@/utils/auth";
import * as XLSX from 'xlsx';
export default {
  name: "Arith-cut-task",
  data() {
    return {
      // 图片处理详情列表
      detail_list: [],
      // 详情弹出床
      detailDialog: false,
      upload: {
        // 是否禁用上传
        isUploading: false,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/common/upload",
        // 上传的文件列表
        fileList: []
      },
      // 文件数据
      fileData: '',
      // 详情遮罩层
      detailLoading: true,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 成列切图任务表格数据
      ArithCutTaskList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        requestId: null,
        orderByColumn: 'id',
        isAsc: 'desc'
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    // 确定切图
    handleStartCut(row) {
      handleCutImage(row.requestId).then((res) => {
        if (res.code === 200) {
          this.$message.success("任务" + row.requestId + "开始切图……请等待状态变更为'处理完成'")
          this.getList()
        }
      }).catch((err) => {
        this.$message.error("开始切图失败！原因：" + err.message)
      })
    },
    // 获取详情
    handleDetail(row) {
      this.detailLoading = true
      getArithCutTaskDetails(row.id).then((res) => {
        if (res.code === 200) {
          this.detailLoading = false
          this.detailDialog = true
          this.detail_list = res.data
        }
      })
    },
    // 下载
    handleDownload(row) {
      let loading = this.$loading({
        lock: true,
        text: '下载中...大概耗时1~30秒,请稍等😀',
        background: 'rgba(0,0,0,0.5)',
        color: 'white'
      })
      let formData = new FormData()
      formData.append("requestId", row.requestId)
      downloadMinImgZip(formData).then((res) => {
        if (res.type == "application/x-download") {
          var debug = res;
          if (debug) {
            var elink = document.createElement('a');
            elink.download = '小图切割压缩包' + '.zip';
            elink.style.display = 'none';
            var blob = new Blob([debug], { type: 'application/x-msdownload' });
            elink.href = URL.createObjectURL(blob);
            document.body.appendChild(elink);
            elink.click();
            document.body.removeChild(elink);
            this.$message.success("识别结果压缩包下载成功")
          } else {
            this.$message.error('导出异常请联系管理员');
          }
        } else {
          const fileReader = new FileReader();
          fileReader.readAsText(res);
          let that = this
          fileReader.onload = function (event) {
            const jsonData = JSON.parse(event.target.result);
            // 在这里使用 jsonData 进行后续操作
            that.$message.error(jsonData.msg)
          };
        }
      }).finally(() => {
        loading.close() // 去掉loading
      })
    },
    // 文件上传成功后的钩子函数
    handleFileSuccess(response, file, fileList) {
      this.upload.isUploading = false;
      this.upload.fileList = []
      this.$modal.msgSuccess(response.msg);
    },
    /**上传excel */
    fileUpload(file, fileList) {
      if (!file) {
        this.$confirm("读取excel文件数据失败，请先上传文件！", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
        })
        // 如果没有文件 - 当然也可以提醒用户弹个警告框 但是基本没有这种情况的出现
        return false;
      } else if (!/\.(xls|xlsx)$/.test(file.name.toLowerCase())) {
        // 文件格式的判断
        this.$message.error("上传格式不正确，请上传xls或者xlsx格式");
        return false;
      }
      const fileReader = new FileReader(file);
      fileReader.onload = (ev) => {
        try {
          const data = ev.target.result;
          const workbook = XLSX.read(data, {
            type: "binary",
          });
          // 取第一张表
          const wsname = workbook.SheetNames[0];
          // 生成json表格内容
          const ws = XLSX.utils.sheet_to_json(workbook.Sheets[wsname]);
          console.log('ws', ws);

          // 循环 ws 取得其中的数据 
          // 把 ws 打印出来 就可以看得很清楚了 之后就进行自己想要的操作就可以了
          // 没有一样的代码 没有一样的需求
          var temporary = '';
          for (let i = 0; i < ws.length; i++) {
            temporary += ws[i].图片url + ','
            //temporary.push(ws[i].图片url)
            // temporary.push([
            // ws[i].设备id + "",
            // ws[i].设备名称
            // ws[i].一级分销客手机号 + "",
            // ws[i].一级真实姓名,
            // ws[i].一级归属门店,
            // ws[i].二级分销客手机号 + "",
            // ws[i].二级真实姓名,
            // ws[i].二级归属门店,
            // ]);
          }
          console.log('temporary', temporary);

          // this.DistributorList = temporary;
          if (temporary.length > 0) {
            this.$notify({
              title: '提示',
              message: '图片上传中,请稍后…',
              offset: 700,
              duration: 0
            });
            
            const excelData = new FormData()
            excelData.append("imageUrls", temporary);
            uploadImage(excelData)
              .then((res) => {
                if (res.code === 200) {
                  this.$message.success("任务添加成功！taskId为:" + res.msg)
                  this.getList()
                  this.$notify.closeAll();//去掉交互框
                }
              })
              .catch((err) => {
                this.$notify.closeAll();//去掉交互框
                this.$message.error("开始切图失败！原因：" + err.message)
              })
          } else {
            this.$message({
              type: "info",
              message: "temporary列表为空，请检查表格是否有数据!",
            });
          }

        } catch (e) {
          return false;
        }
      };
      // 如果为原生 input 则应是 files[0]
      fileReader.readAsBinaryString(file.raw);
    },
    //读取excel的数据
    readExcel(e) {
      let that = this;
      const files = that.fileData;

    },
    handleRemove(file, fileList) {
      this.upload.fileList = fileList
    },
    // fileList长度改变时触发
    changeFileList(file, fileList) {
      // 限制上传的图片类型
      if (file.raw.type == 'image/jpeg' || file.raw.type == 'image/png') {
        this.upload.fileList = fileList
        this.uploadPicNum = this.upload.fileList.length
        // 限制最大上传张数
        if (this.uploadPicNum > 20) {
          // 防抖
          if (this.timer) {
            // 次数>1时，清空之前的定时器
            clearTimeout(this.timer)
            this.timer = setTimeout(() => {
              this.$message.warning("当前一个任务仅支持20张，已删除第21张及之后的图片")
            }, 1000)
          } else {
            // 第一次
            this.timer = setTimeout(() => {
              this.$message.warning("当前一个任务仅支持20张，已删除第21张及之后的图片")
            }, 1000)
          }
          this.upload.fileList.splice(20, 1)
          this.uploadPicNum = this.shelter_fileList.length
        }
      } else {
        this.$message.warning("当前仅支持jpg和png格式的图片")
        var index = this.upload.fileList.indexOf(file)
        this.upload.fileList.splice(index, 1)
      }
      // this.upload.fileList = fileList
    },
    getfileData() {
      // 此处的form是表单中的其它绑定值
      return this.form
    },
    submitUpload() {
      // if(this.upload.fileList)
      // 创建FormData对象，用于携带数据传递到后端
      this.fileData = new FormData()
      this.$refs.upload.submit();
      // this.fileData.append("data", JSON.stringify(this.form));
      this.fileData.append("headers", { Authorization: "Bearer " + getToken() });
      this.fileData.append("withCredentials", false)
      this.fileData.append("filename", "file");
      // this.fileData.append("remark",this.form.remark)
      var i = this.upload.fileList.length
      if (i !== 0) {
        let loading = this.$loading({
          lock: true,
          text: '任务建立中……请稍等😀',
          background: 'rgba(0,0,0,0.5)',
          color: 'white'
        })
        // 此处执行调用发送请求
        addArithCutTask(this.fileData).then((res) => {
          console.log("上传成功回调", res)
          if (res.code === 200) {
            this.$message.success("任务添加成功！taskId为:" + res.msg)
            this.open = false
            this.getList()
          }
          // if(res.type == "application/x-download"){
          //   var debug = res;
          //   if (debug) {
          //       var elink = document.createElement('a');
          //       elink.download = '小图切割压缩包'+'.zip';
          //       elink.style.display = 'none';
          //       var blob = new Blob([debug], { type: 'application/x-msdownload' });
          //       elink.href = URL.createObjectURL(blob);
          //       document.body.appendChild(elink);
          //       elink.click();
          //       document.body.removeChild(elink);
          //       this.$message.success("识别结果压缩包下载成功")
          //   } else {
          //       this.$message.error('导出异常请联系管理员');
          //   }
          // }else{
          //   const fileReader = new FileReader();
          //   fileReader.readAsText(res);
          //   let that = this
          //   fileReader.onload = function(event) {
          //     const jsonData = JSON.parse(event.target.result);
          //     // 在这里使用 jsonData 进行后续操作
          //     that.$message.error(jsonData.msg)
          //   };
          // }
        }).finally(() => {
          loading.close() // 去掉loading

        })

      } else {
        //如果没有文件要上传在此处写逻辑
      }
    },
    // 图片上传
    HttpUploadFile(file) {
      this.fileData.append('files', file.file); // append增加数据
    },
    /** 查询成列切图任务列表 */
    getList() {
      this.loading = true;
      listArithCutTask(this.queryParams).then(response => {
        // this.ArithCutTaskList = response.rows.reverse();
        this.ArithCutTaskList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        requestId: null,
        dirPath: null,
        status: null,
        total: null,
        failCount: null,
        successCount: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null,
        removed: null
      };
      this.upload.fileList = []
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加成列切图任务";
    },
    /** 修改按钮操作 */
    // handleUpdate(row) {
    //   this.reset();
    //   const id = row.id || this.ids
    //   getArithCutTask(id).then(response => {
    //     this.form = response.data;
    //     this.open = true;
    //     this.title = "修改成列切图任务";
    //   });
    // },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除成列切图任务编号为"' + ids + '"的数据项？').then(function () {
        // 修改为逻辑删除
        return removedArithCutTask(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => { });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('genius/arith-cut-task/export', {
        ...this.queryParams
      }, `arith-cut-task_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
